<template>
	<view class="uni-combox" :class="border ? '' : 'uni-combox__no-border'">
		<view class="uni-combox__input-box">
			<input class="uni-combox__input" type="text" :placeholder="placeholder" 
			placeholder-class="uni-combox__input-plac" v-model="inputVal" @input="onInput" @focus="onFocus" 
@blur="onBlur" />
			<!-- <uni-icons :type="showSelector? 'top' : 'bottom'" size="14" color="#999" @click="toggleSelector">
			</uni-icons> -->
		</view>
		<view v-if="showSelector" class="mask mask-zoom mask-show"
			style="background-color: rgba(0, 0, 0, 0); z-index: 10011; transition: all 0.3s ease-in-out 0s;"
			@click="onMask" @touchmove.stop.prevent="moveHandle"></view>
		<view class="uni-combox__selector" :class="'uni-combox__selector-' + position" v-if="showSelector">
			<view class="uni-popper__arrow"></view>
			<scroll-view scroll-y="true" class="uni-combox__selector-scroll">
				<view class="uni-combox__selector-empty" v-if="filterCandidatesLength === 0">
					<text>{{emptyTips}}</text>
				</view>
				<view class="uni-combox__selector-item" v-for="(item,index) in filterCandidates" :key="index" 
				@click="onSelectorClick(item, index)">
					<text>{{item.text}}</text>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	/**
	 * citySelect 组合输入框
	 * @description 组合输入框一般用于既可以输入也可以选择的场景
	 * @tutorial https://ext.dcloud.net.cn/plugin?id=1261
	 * @property {String} label 左侧文字
	 * @property {String} labelWidth 左侧内容宽度
	 * @property {String} placeholder 输入框占位符
	 * @property {Array} candidates 候选项列表
	 * @property {String} emptyTips 筛选结果为空时显示的文字
	 * @property {String} value 组合框的值
	 */
	export default {
		name: 'citySelect',
		emits: ['input', 'update:modelValue'],
		props: {
			cityList: {
				type: Array,
				default () {
					return []
				}
			},
			border: {
				type: Boolean,
				default: true
			},
			label: {
				type: String,
				default: ''
			},
			labelWidth: {
				type: String,
				default: 'auto'
			},
			// placeholder: {
			// 	type: String,
			// 	default: ''
			// },
			candidates: {
				type: Array,
				default () {
					return []
				}
			},
			emptyTips: {
				type: String,
				default: '无匹配项'
			},
			position: {
				type: String,
				default: 'left'
			},
			// #ifndef VUE3
			value: {
				type: [String, Number],
				default: ''
			},
			// #endif
			// #ifdef VUE3
			modelValue: {
				type: [String, Number],
				default: ''
			},
			// #endif
		},
		data() {
			return {
				showSelector: false,
				inputVal: '',
				selectPlaceholder: '',
				cityVal: '',
				
				placeholder: '',
				
				provinceAllList: [],
				cityAllList: [],
				
				isInput: false,
				showMask: false,
			}
		},
		computed: {
			filterCandidates() {
				return this.cityAllList.filter(item => {
					return item.text.toString().indexOf(this.inputVal) > -1
				})
			},
			filterCandidatesLength() {
				return this.filterCandidates.length
			}
		},
		watch: {
			// #ifndef VUE3
			value: {
				handler(newVal) {
					let node = this.cityAllList.find(item => item.value == newVal)
					this.inputVal = node ? node.label : '全国'
					this.isInput = true
				},
				immediate: true
			},
			// #endif
			// #ifdef VUE3
			modelValue: {
				handler(newVal) {
					let node = this.cityAllList.find(item => item.value == newVal)
					this.inputVal = node ? node.label : '全国'
					this.isInput = true
				},
				immediate: true
			},
			// #endif
			cityList: {
				handler(newVal) {
					console.log(newVal)
					let list = JSON.parse(JSON.stringify(newVal))
					// this.provinceAllList = this.formatFlatteningRoutes(newVal).filter(item => item.parent == null)
					let list0 = [{
						label: "全国",
						text: "全国",
						value: "0",
						parent: null
					}]
					this.cityAllList = list0.concat(this.formatFlatteningRoutes(list).filter(item => item.parent != null)) 
				},
				deep: true,
				immediate: true
			}
		},
		methods: {
			toggleSelector() {
				this.showSelector = !this.showSelector
				this.isInput = false
			},
			onFocus() {
				this.showSelector = true
				
				this.placeholder = this.inputVal
				this.inputVal = ""
				this.isInput = false
			},
			onBlur() {
				setTimeout(() => {
					if (this.isInput) {
						this.showSelector = false
						
						if (this.placeholder && (this.value || this.modelValue)) {
							this.inputVal = this.placeholder
						}
					}
				}, 153)
			},
			onSelectorClick(item, index) {
				this.inputVal = item.label
				this.placeholder = ""
				this.showSelector = false
				this.$emit('input', item.value)
				this.$emit('update:modelValue', item.value)
			},
			onInput() {
				// setTimeout(() => {
				// 	this.$emit('input', this.inputVal)
				// 	this.$emit('update:modelValue', this.inputVal)
				// })
			},
			onMask() {
				this.showSelector = !this.showSelector
				
				if (!this.showSelector && this.placeholder && (this.value || this.modelValue)) {
					this.inputVal = this.placeholder
				}
			},
			moveHandle() {},
			// 多维数组转一维
			formatFlatteningRoutes(list) {
				list = list || []
			  if (list.length === 0) return list;
			  let hierarchyList = this.buildHierarchyTree(list);
			  for (let i = 0; i < hierarchyList.length; i++) {
			    if (hierarchyList[i].children) {
			      hierarchyList = hierarchyList
			        .slice(0, i + 1)
			        .concat(hierarchyList[i].children, hierarchyList.slice(i + 1));
			    }
			  }
			  return hierarchyList;
			},
			// 数组创建层级关系
			buildHierarchyTree(tree, pathList, labelList) {
				if (!Array.isArray(tree)) {
					return [];
				}
				if (!tree || tree.length === 0) return [];
				pathList = pathList || []
				labelList = labelList || []
				for (let i = 0; i < tree.length; i++) {
					tree[i].parent = pathList && pathList.length ? pathList[pathList.length - 1] : null;
					tree[i].text = labelList.length ? labelList.join('') + tree[i].label : tree[i].label;
					tree[i].pathList = [...pathList, tree[i].value];
					tree[i].labelList = [...labelList, tree[i].label];
					const hasChildren = tree[i].children && tree[i].children.length > 0;
					if (hasChildren) {
						this.buildHierarchyTree(tree[i].children, tree[i].pathList, tree[i].labelList);
					}
				}
				return tree;
			},
		}
	}
</script>

<style lang="scss" scoped>
	.uni-combox {
		font-size: 14px;
		border: 1px solid #DCDFE6;
		border-radius: 4px;
		padding: 6px 10px;
		position: relative;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		// height: 40px;
		flex-direction: row;
		align-items: center;
		// border-bottom: solid 1px #DDDDDD;
	}

	.uni-combox__label {
		font-size: 16px;
		line-height: 22px;
		padding-right: 10px;
		color: #999999;
	}

	.uni-combox__input-box {
		position: relative;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex: 1;
		flex-direction: row;
		align-items: center;
	}

	.uni-combox__input {
		flex: 1;
		font-size: 14px;
		height: 22px;
		line-height: 22px;
		mex-height: 44px;
		width: 100%;
	}

	.uni-combox__input-plac {
		font-size: 14px;
		color: #999;
	}

	.uni-combox__selector {
		/* #ifndef APP-NVUE */
		box-sizing: border-box;
		/* #endif */
		position: absolute;
		top: calc(100% + 12px);
		// left: 0;
		width: 210%;
		background-color: #FFFFFF;
		border: 1px solid #EBEEF5;
		border-radius: 6px;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		z-index: 10012;
		padding: 4px 0;
	}
	.uni-combox__selector-left {
		left: 0;
	}
	.uni-combox__selector-right {
		right: 0;
	}

	.uni-combox__selector-scroll {
		/* #ifndef APP-NVUE */
		max-height: 200px;
		box-sizing: border-box;
		/* #endif */
	}

	.uni-combox__selector-empty,
	.uni-combox__selector-item {
		/* #ifndef APP-NVUE */
		display: flex;
		cursor: pointer;
		/* #endif */
		line-height: 18px;
		font-size: 14px;
		text-align: left;
		border-bottom: solid 1px #DDDDDD;
		padding: 10px 10px;
		text-overflow: ellipsis;
		display: -webkit-box;  //使用自适应布局
		-webkit-line-clamp: 2;  //设置超出行数，要设置超出几行显示省略号就把这里改成几
		-webkit-box-orient: vertical;
	}

	.uni-combox__selector-item:hover {
		background-color: #f9f9f9;
	}

	.uni-combox__selector-empty:last-child,
	.uni-combox__selector-item:last-child {
		/* #ifndef APP-NVUE */
		border-bottom: none;
		/* #endif */
	}

	// picker 弹出层通用的指示小三角
	.uni-popper__arrow,
	.uni-popper__arrow::after {
		position: absolute;
		display: block;
		width: 0;
		height: 0;
		border-color: transparent;
		border-style: solid;
		border-width: 6px;
	}

	.uni-popper__arrow {
		filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.03));
		top: -6px;
		// left: 10%;
		margin-right: 3px;
		border-top-width: 0;
		border-bottom-color: #EBEEF5;
	}
	.uni-combox__selector-left .uni-popper__arrow {
		left: 10%;
	}
	.uni-combox__selector-right .uni-popper__arrow {
		right: 10%;
	}

	.uni-popper__arrow::after {
		content: " ";
		top: 1px;
		margin-left: -6px;
		border-top-width: 0;
		border-bottom-color: #fff;
	}

	.uni-combox__no-border {
		border: none;
	}
	
	.mask {
	  position: fixed;
	  top: 0;
	  left: 0;
	  right: 0;
	  bottom: 0;
	  opacity: 0;
	  pointer-events: auto;
	  transition: -webkit-transform 0.3s;
	  transition: transform 0.3s;
	  transition: transform 0.3s, -webkit-transform 0.3s;
	}
	.mask-zoom {
	  transform: scale(1.2, 1.2);
	}
	.mask-show {
	  opacity: 1;
	}
</style>
